﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

namespace VOEISHubPushServiceClient
{
    class VOEISHubAPI : IHubAPI
    {
        private string _APIKey;
        private string _HubURL;
        private long _PushInterval;
        private int _HubTimeout;
        
        public string APIKey
        {
            get
            {
                return _APIKey;
            }
            set
            {
                _APIKey = value;
            }
        }

        public string HubURL
        {
            get
            {
                return _HubURL;
            }
            set
            {
                _HubURL = value;
            }
        }

        public long PushInterval
        {
            get
            {
                return _PushInterval;
            }
            set
            {
                _PushInterval = value;
            }
        }

        public int HubTimeout
        {
            get
            {
                return _HubTimeout;
            }
            set
            {
                _HubTimeout = value;
            }
        }

        public VOEISHubAPI()
        {
            ServiceConfigurationManager scm = new ServiceConfigurationManager();

            Dictionary<string, string> APIDictionary = new Dictionary<string, string>();
            APIDictionary = scm.ReadHubAPISettings();

            _APIKey = APIDictionary["APIKey"];
            _HubURL = APIDictionary["VOEISHubURL"];
            _PushInterval = long.Parse(APIDictionary["DataCheckInterval"]);
            _HubTimeout = int.Parse(APIDictionary["HubTimeout"]);
        }

        public void LoadAPISettings(string TemplatePath)
        {
            ServiceConfigurationManager scm = new ServiceConfigurationManager();

            Dictionary<string,string> APIDictionary = new Dictionary<string,string>();
            scm.ApplicationConfigPath = TemplatePath;
            APIDictionary = scm.ReadHubAPISettings();

            _APIKey = APIDictionary["APIKey"];
            _HubURL = APIDictionary["VOEISHubURL"];
            _PushInterval = long.Parse(APIDictionary["DataCheckInterval"]);
            _HubTimeout = int.Parse(APIDictionary["HubTimeout"]);
        }
        public string GetProjectTemplates(string ProjectID)
        {
            //Create the web request and set some basic parameters
            HttpWebRequest request = default(HttpWebRequest);
            WebResponse response = null;
            StreamReader reader = default(StreamReader);
            string retString = "";

            try
            {
                // Submit the request
                request = (HttpWebRequest)WebRequest.Create(_HubURL.Replace("&lt;projectID&gt;", ProjectID) + "get_project_data_templates.json?");

                // Get response  
                response = (HttpWebResponse)request.GetResponse();

                // Get the response stream into a reader  
                reader = new StreamReader(response.GetResponseStream());

                //Save the response to a string
                string str = reader.ReadToEnd();

                //str = "[{""name"":""SandboxTest_003"",""updated_at"":""2011-02-21T09:24:52-06:00"",""id"":1,""type"":""Sensor"",""filename"":""temp_data/Mon Feb 21 09:19:40 -0700 2011HLSandboxFile_003.txt"",""start_line"":2,""description"":""Template creation of a simple file so that I can try a curl command and get the header actions for the service I am writing.""},{""name"":""Sandbox4"",""updated_at"":""2011-02-28T13:11:18-06:00"",""id"":2,""type"":""Sensor"",""filename"":""temp_data/Mon Feb 28 13:10:57 -0700 2011HLSandboxFile_003.csv"",""start_line"":2,""description"":""""},{""name"":""Sandbox5"",""updated_at"":""2011-02-28T14:25:32-06:00"",""id"":3,""type"":""Sensor"",""filename"":""temp_data/Mon Feb 28 14:25:15 -0700 2011HLSandboxFile_003.csv"",""start_line"":2,""description"":""""},{""name"":""HBSSandbox_004"",""updated_at"":""2011-03-02T14:26:12-06:00"",""id"":4,""type"":""Sensor"",""filename"":""temp_data/Wed Mar 02 14:21:20 -0700 2011HLSandboxFile_004.txt"",""start_line"":1,""description"":""Sandbox file containing no header, local date and time, depth offset, and tempc.  This is used for testing so that I can get a template, perform cURL, monitor with fiddler, and reproduce the headers in .NET.""}]"
                //Deserialize the json string
                //TODO: Write a class to deserialize the json
                if (str.Length > 0)
                {
                    try
                    {
                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        dynamic lstDataTemplates = serializer.DeserializeObject(str);
                        str = null;
                        foreach (object obj in lstDataTemplates)
                        {
                            foreach (KeyValuePair<string, object> kvp in (IDictionary<string, object>)obj)
                            {
                                retString = retString + kvp.Key.ToString() + ": " + kvp.Value.ToString() + System.Environment.NewLine;
                            }
                            retString = retString + System.Environment.NewLine;
                        }

                    }
                    catch (Exception ex)
                    {
                        //Catch our errors and write them to the event log and send an email
                        System.Diagnostics.EventLog.WriteEntry("VOEIS Hub Push Service - cURL Push", "Error uploading file: " + System.Environment.NewLine + ex.Message.ToString());
                    }
                }

            }
            catch (Exception ex)
            {
                //Catch our errors and write them to the event log and send an email
                System.Diagnostics.EventLog.WriteEntry("VOEIS Hub Push Service - cURL Push", "Error uploading file: " + System.Environment.NewLine + ex.Message.ToString());

                //Make sure that we close the response if it is still alive
                if (response != null)
                {
                    response.Close();
                    response = null;
                }

            }
            finally
            {
                //Make sure that we close our response
                request = null;
            }

            return retString;
        }
    }
}
